package com.indusfo.spc.service.impl;


import com.indusfo.spc.exception.GlobalException;
import com.indusfo.spc.exception.ModifyFailedException;
import com.indusfo.spc.exception.ParamsErrorException;
import com.indusfo.spc.mapper.*;
import com.indusfo.spc.pojo.*;
import com.indusfo.spc.service.ProcessVerService;
import com.indusfo.spc.vo.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;

/**
 * 类说明:工艺版本 业务实现类
 * 
 * @author 王辉
 * 
 * @version 创建时间：2018年12月10日 上午10:11:58
 */
@Service
public class ProcessVerServiceImpl implements ProcessVerService {
	//日志记录
	private static final Logger logger = LoggerFactory.getLogger(ProcessVerServiceImpl.class);

	@Autowired
	private ProcessVerMapper processVerMapper;

	@Autowired
	private MaterialXOMapper materialXOMapper;

	@Autowired
	private ProcessFlowMapper processFlowMapper;

	@Autowired
	private ProcessStaMapper  processStaMapper;
	@Autowired
	private ProcessTargetMapper  processTargetMapper;

	@Autowired
	private ProcessBomMapper  processBomMapper;
	@Autowired
	private ProcessBlxxMapper  processBlxxMapper;

	@Autowired
	private ProcessOfflineMapper  processOfflineMapper;
	@Autowired
	private ProcessExchangeMapper processExchangeMapper;
	@Autowired
	private ProcessOfflineListMapper processOfflineListMapper;
	@Autowired
	private ProListMapper proListMapper;
	@Autowired
	private OfflineListMapper offlineListMapper;

	@Override
	public JSONObject queryProcessVer(ProcessVer processVer) {
		try {
			// 调用Mapper分页查询方法
			List<ProcessVer> listForPage = processVerMapper.queryProcessVer(processVer);
			// 判断是否查询到数据
			Integer count = processVerMapper.countProcessVer(processVer);
			return JSONObject.oK(listForPage, count);
		} catch (GlobalException e) {
			// 捕获异常,打印并返回数
			logger.error(e.getMessage(), e);
			return JSONObject.build(500, e.getMessage());
		}
	}

	@Override
	public JSONObject insertOrUpdateProcessVer(ProcessVer processVer) {
		try{
			if(processVer.getlDataState()==null){
				processVer.setlDataState(1);
			}
			if(processVer.getlProduct()==null){
				processVer.setlProduct(processVer.getlMatId());
			}
			if(processVer.getlMatId()==null){
				processVer.setlMatId(processVer.getlProduct());
			}
			if(processVer.getlCreater()==null){
				processVer.setlCreater(1);
			}
			if(processVer.getdCreateTime()==null){
				processVer.setdCreateTime(new Date());
			}
			validate(processVer);



			if (processVer.getlProVer()!=null) {// 有id,做更新

				Integer row = processVerMapper.updateByPrimaryKeySelective(processVer);
				if(row == 0) {
					throw new ModifyFailedException("更新失败！");
				}
				return JSONObject.oK("更新成功！", processVer.getlProVer());
			}else {// 没id,做新增
				// 校验传入参数

				Integer row = processVerMapper.insertSelective(processVer);
				if(row == 0) {
					throw new ModifyFailedException("新增失败！");
				}
				return JSONObject.oK("新增成功！",  processVer.getlProVer());
			}




		}catch (GlobalException e){
			logger.error(e.getMessage());
			return JSONObject.build(500, e.getMessage());
		}
	}

	@Override
	public JSONObject deleteProcessVer(List<Integer> lProVerIds, Integer lDataState) {
		try {
			//1.校验
			if(lProVerIds == null) {
                throw new ParamsErrorException("id不能为空");
            }
			if(lDataState == null) {
                throw new ParamsErrorException("状态不能为空");
            }
			int row = processVerMapper.deleteProcessVer(lProVerIds,lDataState);
			String msg = "";
			switch (lDataState) {
				case 1:
					msg = "启用";
					break;
				case 2:
					msg = "删除";
					break;
				case 3:
					msg = "停用";
			}

			if (row == 0) {
				// 判断传入的数据状态参数lDataState,返回相应信息
				throw new ModifyFailedException(msg+"失败!");
			}
			return JSONObject.oK(msg+"成功！", row);
		}catch (GlobalException e){
			logger.error(e.getMessage());
			return JSONObject.build(500, e.getMessage());
		}
	}

	@Override
	public JSONObject leadProcessVer(Integer matId,Integer lProVer, Integer isOffine, Integer isSta, Integer isTarget, Integer isBom, Integer isBlxx) {
		try {
			//1.校验
			if(matId == null){
				throw new ParamsErrorException("产品编号不能为空");
			}
			if(lProVer == null){
				throw new ParamsErrorException("标准流程编号不能为空");
			}
			isOffine=isOffine==null?0:isOffine;
			isSta=isSta==null?0:isSta;
			isTarget=isTarget==null?0:isTarget;
			isBom=isBom==null?0:isBom;
			isBlxx=isBlxx==null?0:isBlxx;

			//导入必导项
			//查询  查询成功
			ProcessVer processVer=new ProcessVer();
			processVer.setlProVer(lProVer);
			List<ProcessVer> processVers = processVerMapper.queryProcessVer(processVer);
			if(processVers.size()!=0){
				processVer=processVers.get(0);
			}
				if(processVer.getVcVersion()==null){

					processVer.setVcVersion("异常导入的标准流程");
				}
			processVer.setlProVer(null);
			processVer.setlDataState(1);
			processVer.setlProduct(matId);
			processVer.setlMatId(matId);
			processVer.setdCreateTime(new Date());
			//新增版本呢成功

			if(processVerMapper.countParamsNotRepeat(processVer)!=0){
				throw new ParamsErrorException("已存在该版本");

			}

			processVerMapper.insertSelective(processVer);
			Integer newlProVer=processVer.getlProVer();
			//版本导入成功

			//导入流程
			ProcessFlow processFlow=new ProcessFlow();
			processFlow.setlProVer(lProVer);
			//查询原有流程  查询流程成功
			List<ProcessFlow> processFlows = processFlowMapper.listProcessFlow(processFlow);
			for (ProcessFlow flow:processFlows
				 ) {
				Integer oldlProFlow=flow.getlProFlow();
				//创建新流程
				ProcessFlow newflow=new ProcessFlow();
				newflow.setlDataState(1);
				newflow.setlProVer(newlProVer);
				newflow.setlProId(flow.getlProId());
				newflow.setlProFlow(null);
				newflow.setWhetherSequence(1);
				//新增流程
				 processFlowMapper.insertProcessFlow(newflow);
				//导入流程完成
				//导入选择的功能
				Integer newlProFlow=newflow.getlProFlow();


				//导入工位
				if(isSta!=0){
					//查询工位
					ProcessSta processSta=new ProcessSta();
					processSta.setlProFlow(oldlProFlow);
					List<ProcessSta> processStas = processStaMapper.queryProcessSta(processSta);
					for (ProcessSta sta:processStas
						 ) {
						sta.setlProFlow(newlProFlow);
						//添加工位
						sta.setProcessStaId(null);
						sta.setDataState(1);
						processStaMapper.insertProcessSta(sta);
					}
//					System.out.println("导入工位成功");

				}
				//导入检测
				if(isTarget!=0){
					//查询工位
					ProcessTarget processTarget=new ProcessTarget();
					processTarget.setlProFlow(oldlProFlow);
					List<ProcessTarget> processTargets = processTargetMapper.queryProcessTarget(processTarget);
					for (ProcessTarget target:processTargets
					) {
						target.setlProFlow(newlProFlow);
						//添加工位
						target.setlProTarget(null);
						processTargetMapper.insertProcessTarget(target);
					}
//					System.out.println("导入检测成功");
				}

				//导入物料
				if(isBom!=0){
					//查询工位
					ProcessBom processBom=new ProcessBom();
					processBom.setlProFlow(oldlProFlow);
					List<ProcessBom> processBoms = processBomMapper.queryProcessBom(processBom);
					for (ProcessBom bom:processBoms
					) {
						bom.setlProFlow(newlProFlow);
						//添加工位
						bom.setProcessBomId(null);
						processBomMapper.insertProcessBom(bom);
					}
//					System.out.println("导入物料成功");
				}
				//导入不良
				if(isBlxx!=0){
					//查询工位
					ProcessBlxx processBlxx=new ProcessBlxx();
					processBlxx.setlProFlow(oldlProFlow);
					List<ProcessBlxx> processBlxxes = processBlxxMapper.queryProcessBlxx(processBlxx);
					for (ProcessBlxx blxx:processBlxxes
					) {
						blxx.setlProFlow(newlProFlow);
						//添加工位
						blxx.setProcessBlxxId(null);
						processBlxxMapper.insertProcessBlxx(blxx);
					}
//					System.out.println(newlProFlow+"导入不良成功"+flow.getlProFlow());
				}




			}
			//导入维修
			if(isOffine!=0){
				//获取版本下维修
				ProcessOffline processOffline=new ProcessOffline();
				processOffline.setlProVer(lProVer);
				List<ProcessOffline> processOfflines = processOfflineMapper.queryProcessOffline(processOffline);
				//导入维修
				for (ProcessOffline offline:processOfflines
				) {
					//添加工序
					//查询下面工序
					ProcessExchange  processExchange=new ProcessExchange();
					processExchange.setlProVer(lProVer);
					processExchange.setOfflineId(offline.getOfflineId());
					List<ProcessExchange> processExchanges = processExchangeMapper.queryProcessExchange(processExchange);
					for (ProcessExchange exchange:processExchanges
						 ) {
						exchange.setlProVer(newlProVer);
						exchange.setId(null);
						processExchangeMapper.insertProcessExchange(exchange);
					}

					//查询该工序下所以子工序

					OfflineList offlineList=new OfflineList();
					offlineList.setOfflineId(offline.getOfflineId());
					List<OfflineList> OfflineLists = offlineListMapper.selectAll(offlineList);
					for (int i = 0; i <OfflineLists.size() ; i++) {
						ProcessOfflineList processOfflineList=new ProcessOfflineList();
						processOfflineList.setOfflineId(offline.getOfflineId());
						processOfflineList.setOfflineListId(OfflineLists.get(i).getOfflineDetailId());
						processOfflineList.setProVerId(lProVer);
						List<ProcessOfflineList> processOfflineLists = processOfflineListMapper.queryProcessOfflineList(processOfflineList);
						for (ProcessOfflineList processOfflineList1 :processOfflineLists) {
							processOfflineList1.setProVerId(newlProVer);
							processOfflineList1.setProcessOfflineListId(null);
							processOfflineList1.setDataState(1);
							processOfflineListMapper.insertProcessOfflineList(processOfflineList1);
						}


					}





					offline.setlProVer(newlProVer);
					offline.setlProOffline(null);
					processOfflineMapper.insertProcessOffline(offline);
					//维修添加完成



				}


//				System.out.println("导入维修成功");

			}





			return JSONObject.oK("导入成功！", newlProVer);
		}catch (GlobalException e){
			logger.error(e.getMessage());
			return JSONObject.build(500, e.getMessage());
		}
	}

	@Override
	public JSONObject saveProcessFlow(ProcessVer processVer) {
		try {
			//获取数据数据版本id



			if(processVer==null){
				throw new ParamsErrorException("流程不能为空");
			}
			List<ProcessFlow> processFlowList =new ArrayList<>();
			processFlowList=processVer.getProcessFlowList();
			Integer lProVer=processVer.getlProVer();
			if(lProVer==null){
				throw new ParamsErrorException("版本id不能为空");
			}
			//获取数据库数据
			ProcessFlow processFlow1=new ProcessFlow();
			processFlow1.setlProVer(lProVer);
			List<ProcessFlow> oldprocessFlowList=processFlowMapper.listProcessFlow(processFlow1);
			List<Integer> deleteList = DeleteList(oldprocessFlowList, processFlowList);
			int deleterow=0;
			int insertrow=0;
			int updaterow=0;
			if(deleteList.size()!=0){
				deleterow = processFlowMapper.deleteProcessFlow(deleteList, 2);
			}
			//删除完成  进行新增 和 修改
			for (ProcessFlow processFlow:processFlowList
			) {
				if(processFlow.getlDataState()==null){
					processFlow.setlDataState(1);
				}
				if(processFlow.getWhetherSequence()==null){
					processFlow.setWhetherSequence(1);
				}

				if(processFlow.getlProFlow()!=null){
					if(processFlow.getlProFlow().equals(0)){
						processFlow.setlProFlow(null);
						insertrow=insertrow+processFlowMapper.insertProcessFlow(processFlow);
						//带出  工位和不良
						Integer newFlow=processFlow.getlProFlow();
						Integer lProId=processFlow.getlProId();

						//查询工序下工位
					List<Station>	stations = processFlowMapper.queryStationByPro(lProId);
					List<Blxx>	blxxs = processFlowMapper.queryBlxxByPro(lProId);
						for(int i=0;i<stations.size();i++){
							ProcessSta processSta=new ProcessSta();
							processSta.setlProFlow(newFlow);
							processSta.setStaId(stations.get(i).getStaId());
							processSta.setDataState(1);
							processStaMapper.insertProcessSta(processSta);
						}
						for(int i=0;i<blxxs.size();i++){
							ProcessBlxx processBlxx=new ProcessBlxx();
							processBlxx.setBlxxId(blxxs.get(i).getBlxxId());
							processBlxx.setlProFlow(newFlow);
							processBlxx.setDataState(1);
							processBlxxMapper.insertProcessBlxx(processBlxx);

						}
						//带出  工位和不良  完成


					}else{
						updaterow=updaterow+processFlowMapper.updateProcessFlow(processFlow);
					}


				}
			}



			return JSONObject.oK("保存成功",deleterow+insertrow+updaterow);
		} catch (GlobalException e) {// 捕获自定义异常
			logger.error(e.getMessage());
			return JSONObject.build(500, e.getMessage());
		}
	}

	@Override
	public JSONObject saveProcessOffline(ProcessVer processVer) {
		try {
			//获取数据数据版本
			if(processVer==null){
				throw new ParamsErrorException("数据不能为空");
			}

			if(processVer.getlProVer()==null){
				throw new ParamsErrorException("版本不能为空");
			}

//			if(processVer.getProcessOfflines()==null){
//				throw new ParamsErrorException("版本不能为空");
//			}


			//获取list集合
			List<ProcessOffline> processOfflines =new ArrayList<>();
			processOfflines=processVer.getProcessOfflines();
			//获取版本
			Integer lProVer=processVer.getlProVer();
			if(lProVer==null){
				throw new ParamsErrorException("版本id不能为空");
			}
			//获取数据库数据
			ProcessOffline processOffline1=new ProcessOffline();
			processOffline1.setlProVer(lProVer);
			List<ProcessOffline> oldprocessOfflines=processOfflineMapper.queryProcessOffline(processOffline1);

			List<Integer> processOfflineIds=new ArrayList<>();
			List<Integer> oldIds=new ArrayList<>();
			List<Integer> newIds=new ArrayList<>();
			if(oldprocessOfflines!=null) {
				for (ProcessOffline processOffline : oldprocessOfflines
				) {
					oldIds.add(processOffline.getlProOffline());
				}
			}
			if(processOfflines!=null){
				for (ProcessOffline processOffline:processOfflines
				) {
					newIds.add(processOffline.getlProOffline());
				}}


			HashSet h1 = new HashSet(oldIds);
			HashSet h2 = new HashSet(newIds);
			h1.removeAll(h2);
			processOfflineIds.addAll(h1);
			int deleterow=0;
			int insertrow=0;
			int updaterow=0;
			if(processOfflineIds.size()!=0){
				deleterow = processOfflineMapper.deleteProcessOffline(processOfflineIds, 2);
			}
			//删除完成  进行新增 和 修改
			for (ProcessOffline processOffline:processOfflines
			) {
				if(processOffline.getDataState()==null){
					processOffline.setDataState(1);
				}


				if(processOffline.getlProOffline()!=null){
					if(processOffline.getlProOffline().equals(0)){
						processOffline.setlProOffline(null);
						Integer Counts = processOfflineMapper.checkProcessOffline(processOffline);
						if (Counts ==0) {
							insertrow = insertrow + processOfflineMapper.insertProcessOffline(processOffline);
						}

					}else{
						Integer Counts = processOfflineMapper.checkProcessOffline(processOffline);
						if (Counts ==0) {
							updaterow = updaterow + processOfflineMapper.updateProcessOffline(processOffline);
						}
					}


				}
			}



			return JSONObject.oK("保存成功",deleterow+insertrow+updaterow);
		} catch (GlobalException e) {// 捕获自定义异常
			logger.error(e.getMessage());
			return JSONObject.build(500, e.getMessage());
		}
	}

	@Override
	public JSONObject saveProcessExchange(ProcessVer processVer) {
		try {
			//获取数据数据版本
			if(processVer==null){
				throw new ParamsErrorException("数据不能为空");
			}

			if(processVer.getlProVer()==null){
				throw new ParamsErrorException("版本不能为空");
			}
			Integer lProVer=processVer.getlProVer();
			if(processVer.getOfflineId()==null){
				throw new ParamsErrorException("维修id不能为空");
			}
			Integer OfflineId=processVer.getOfflineId();

			//获取list集合
			List<ProcessExchange> processExchanges =new ArrayList<>();
			processExchanges=processVer.getProcessExchanges();
			//获取版本


			//获取数据库数据
			ProcessExchange processExchange1=new ProcessExchange();
			processExchange1.setlProVer(lProVer);
			processExchange1.setOfflineId(OfflineId);
			List<ProcessExchange> oldprocessExchanges=processExchangeMapper.queryProcessExchange(processExchange1);
			//删除动作
			List<Integer> processExchangeIds=new ArrayList<>();
			List<Integer> oldIds=new ArrayList<>();
			List<Integer> newIds=new ArrayList<>();
			if(oldprocessExchanges!=null) {
				for (ProcessExchange processExchange : oldprocessExchanges
				) {
					oldIds.add(processExchange.getId());
				}
			}
			if(processExchanges!=null){
				for (ProcessExchange processExchange:processExchanges
				) {
					newIds.add(processExchange.getId());
				}}


			HashSet h1 = new HashSet(oldIds);
			HashSet h2 = new HashSet(newIds);
			h1.removeAll(h2);
			processExchangeIds.addAll(h1);
			int deleterow=0;
			int insertrow=0;
			int updaterow=0;
			if(processExchangeIds.size()!=0){
				deleterow = processExchangeMapper.deleteProcessExchange(processExchangeIds, 2);
			}
			//删除完成  进行新增 和 修改
			for (ProcessExchange processExchange:processExchanges
			) {
				if(processExchange.getDataState()==null){
					processExchange.setDataState(1);
				}


				if(processExchange.getId()!=null){
					if(processExchange.getId().equals(0)){
						processExchange.setId(null);
						Integer Counts = processExchangeMapper.checkProcessExchange(processExchange);
						if (Counts ==0) {
							insertrow = insertrow + processExchangeMapper.insertProcessExchange(processExchange);
						}

					}else{
						Integer Counts = processExchangeMapper.checkProcessExchange(processExchange);
						if (Counts ==0) {
							updaterow = updaterow + processExchangeMapper.updateProcessExchange(processExchange);
						}
					}


				}
			}



			return JSONObject.oK("保存成功",deleterow+insertrow+updaterow);
		} catch (GlobalException e) {// 捕获自定义异常
			logger.error(e.getMessage());
			return JSONObject.build(500, e.getMessage());
		}
	}

	@Override
	public JSONObject saveProcessOfflineList(ProcessVer processVer) {
		try {
			//获取数据数据版本
			if(processVer==null){
				throw new ParamsErrorException("数据不能为空");
			}

			if(processVer.getlProVer()==null&&processVer.getProVerId()==null){
				throw new ParamsErrorException("版本不能为空");
			}
			Integer lProVer=null;
			if(processVer.getlProVer()!=null){
				 lProVer=processVer.getlProVer();
			}else{
				 lProVer=processVer.getProVerId();
			}
			if(processVer.getOfflineId()==null){
				throw new ParamsErrorException("维修id不能为空");
			}
			Integer OfflineId=processVer.getOfflineId();

			if(processVer.getOfflineListId()==null){
				throw new ParamsErrorException("维修子工序不能为空");
			}
			Integer OfflineListId=processVer.getOfflineListId();

			//获取list集合
			List<ProcessOfflineList> processOfflineLists =new ArrayList<>();
			processOfflineLists=processVer.getProcessOfflineLists();

			//获取数据库数据
			ProcessOfflineList processOfflineList1=new ProcessOfflineList();
			processOfflineList1.setProVerId(lProVer);
			processOfflineList1.setOfflineId(OfflineId);
			processOfflineList1.setOfflineListId(OfflineListId);
			List<ProcessOfflineList> oldprocessOfflineLists=processOfflineListMapper.queryProcessOfflineList(processOfflineList1);

			List<Integer> processOfflineListIds=new ArrayList<>();
			List<Integer> oldIds=new ArrayList<>();
			List<Integer> newIds=new ArrayList<>();
			if(oldprocessOfflineLists!=null) {
				for (ProcessOfflineList processOfflineList : oldprocessOfflineLists
				) {
					oldIds.add(processOfflineList.getProcessOfflineListId());
				}
			}
			if(processOfflineLists!=null){
				for (ProcessOfflineList processOfflineList:processOfflineLists
				) {
					newIds.add(processOfflineList.getProcessOfflineListId());
				}
			}


			HashSet h1 = new HashSet(oldIds);
			HashSet h2 = new HashSet(newIds);
			h1.removeAll(h2);
			processOfflineListIds.addAll(h1);
			int deleterow=0;
			int insertrow=0;
			int updaterow=0;
			if(processOfflineListIds.size()!=0){
				deleterow = processOfflineListMapper.deleteProcessOfflineList(processOfflineListIds, 2);
			}
			//删除完成  进行新增 和 修改
			System.out.println(processOfflineLists.toString());

			for (ProcessOfflineList processOfflineList:processOfflineLists
			) {
				if(processOfflineList.getDataState()==null){
					processOfflineList.setDataState(1);
				}


				if(processOfflineList.getProcessOfflineListId()!=null){
					if(processOfflineList.getProcessOfflineListId().equals(0)){
						processOfflineList.setProcessOfflineListId(null);
						Integer Counts = processOfflineListMapper.checkProcessOfflineList(processOfflineList);
						if (Counts ==0) {
							insertrow = insertrow + processOfflineListMapper.insertProcessOfflineList(processOfflineList);
						}

					}else{
						Integer Counts = processOfflineListMapper.checkProcessOfflineList(processOfflineList);
						if (Counts ==0) {
							updaterow = updaterow + processOfflineListMapper.updateProcessOfflineList(processOfflineList);
						}
					}


				}
			}



			return JSONObject.oK("保存成功",deleterow+insertrow+updaterow);
		} catch (GlobalException e) {// 捕获自定义异常
			logger.error(e.getMessage());
			return JSONObject.build(500, e.getMessage());
		}
	}


	//非空判断
	private void validate(ProcessVer processVer) {
		//名称
		String vcVersion =processVer.getVcVersion();

		Integer matId = processVer.getlMatId();
		Integer product = processVer.getlProduct();
		if(StringUtils.isEmpty(vcVersion)){
			throw new ParamsErrorException("版本名称不能为空");
		}
		if(matId == null){
			throw new ParamsErrorException("物料id不能为空");
		}
		if(product == null){
			throw new ParamsErrorException("产品id不能为空");
		}
		if (vcVersion.getBytes().length > 100){
			throw new ParamsErrorException("版本名称过长");
		}

		int row=processVerMapper.countParamsNotRepeat(processVer);

		if (row != 0) {
			throw new ParamsErrorException("版本名称重复");
		}




	}
	//删除不存在的数据
	private List<Integer> DeleteList(List<ProcessFlow> oldprocessFlowList, List<ProcessFlow> processFlowList) {
		List<Integer> processFlowIds=new ArrayList<>();
		List<Integer> oldIds=new ArrayList<>();
		for (ProcessFlow processFlow:oldprocessFlowList
		) {
			oldIds.add(processFlow.getlProFlow());
		}
		List<Integer>newIds=new ArrayList<>();
		for (ProcessFlow processFlow:processFlowList
		) {
			newIds.add(processFlow.getlProFlow());
		}
		HashSet h1 = new HashSet(oldIds);
		HashSet h2 = new HashSet(newIds);
		h1.removeAll(h2);
		processFlowIds.addAll(h1);
		return processFlowIds;

	}

}
